from fastapi import APIRouter, Depends, HTTPException, Query, Body
from sqlalchemy.orm import Session
from ..database import get_db
from ..models.template import Template
from ..auth.jwt_handler import get_current_user
from ..models.user import User
from pydantic import BaseModel
from typing import Optional, List
import uuid
import datetime
from datetime import timezone
import json

router = APIRouter(
    prefix='/templates',  # 路由前缀
    tags=['templates'],
)

# 定义请求模型
class TemplateCreate(BaseModel):
    name: str
    content: str
    var: str

# 定义响应模型
class TemplateResponse(BaseModel):
    id: str
    name: str
    content: str
    var: str
    created_at: str

    # 配置Pydantic模型从SQLAlchemy模型实例创建
    class Config:
        orm_mode = True
        # 自定义JSON编码器以处理UUID和datetime对象
        json_encoders = {
            uuid.UUID: lambda v: str(v),
            datetime.datetime: lambda v: v.isoformat()
        }

# 获取所有模板
@router.get('/', response_model=List[TemplateResponse])
def get_templates(
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
    name: Optional[str] = Query(None)
):
    query = db.query(Template)

    if name:
        query = query.filter(Template.name.like(f'%{name}%'))

    templates = query.order_by(Template.created_at.desc()).all()
    
    # 手动转换每个模板对象
    result = []
    for template in templates:
        template_dict = {
            "id": str(template.id),
            "name": template.name,
            "content": template.content,
            "var": template.var,
            "created_at": template.created_at.isoformat() if template.created_at else None
        }
        result.append(template_dict)
    
    return result

# 获取单个模板
@router.get('/{template_id}', response_model=TemplateResponse)
def get_template(
    template_id: str,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    template = db.query(Template).filter(Template.id == template_id).first()
    
    if not template:
        raise HTTPException(status_code=404, detail="模板不存在")
    
    # 手动转换模板对象
    return {
        "id": str(template.id),
        "name": template.name,
        "content": template.content,
        "var": template.var,
        "created_at": template.created_at.isoformat() if template.created_at else None
    }

# 创建新模板
@router.post('/', response_model=TemplateResponse)
def create_template(
    template_data: TemplateCreate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    template_id = str(uuid.uuid4())
    new_template = Template(
        id=template_id,
        name=template_data.name,
        content=template_data.content,
        var=template_data.var
    )
    db.add(new_template)
    db.commit()
    db.refresh(new_template)
    
    # 手动转换新创建的模板对象
    return {
        "id": str(new_template.id),
        "name": new_template.name,
        "content": new_template.content,
        "var": new_template.var,
        "created_at": new_template.created_at.isoformat() if new_template.created_at else None
    }

# 删除模板
@router.delete('/{template_id}')
def delete_template(
    template_id: str,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    template = db.query(Template).filter(Template.id == template_id).first()
    
    if not template:
        raise HTTPException(status_code=404, detail="模板不存在")
    
    db.delete(template)
    db.commit()
    
    return {"message": "删除成功"}

# 更新模板
@router.put('/{template_id}', response_model=TemplateResponse)
def update_template(
    template_id: str,
    template_data: TemplateCreate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    template = db.query(Template).filter(Template.id == template_id).first()
    
    if not template:
        raise HTTPException(status_code=404, detail="模板不存在")
    
    # 更新模板信息
    template.name = template_data.name
    template.content = template_data.content
    template.var = template_data.var
    
    db.commit()
    db.refresh(template)
    
    # 手动转换模板对象
    return {
        "id": str(template.id),
        "name": template.name,
        "content": template.content,
        "var": template.var,
        "created_at": template.created_at.isoformat() if template.created_at else None
    }